import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_text_styles.dart';
import '../../core/constants/app_constants.dart';
import '../../core/constants/emotion_constants.dart';
import '../../core/routes/app_routes.dart';

import '../../controllers/emotion_controller.dart';

/// 今日总结组件
/// Daily summary widget showing today's emotion statistics
class DailySummaryWidget extends StatefulWidget {
  /// 是否显示详细信息
  /// Whether to show detailed information
  final bool showDetails;
  
  /// 是否可点击
  /// Whether clickable
  final bool clickable;

  const DailySummaryWidget({
    super.key,
    this.showDetails = true,
    this.clickable = true,
  });

  @override
  State<DailySummaryWidget> createState() => _DailySummaryWidgetState();
}

class _DailySummaryWidgetState extends State<DailySummaryWidget>
    with TickerProviderStateMixin {
  late AnimationController _animationController;
  late AnimationController _progressController;
  late List<Animation<double>> _itemAnimations;
  late Animation<double> _progressAnimation;
  
  final EmotionController _emotionController = Get.find<EmotionController>();
  
  @override
  void initState() {
    super.initState();
    _initAnimations();
  }

  @override
  void dispose() {
    _animationController.dispose();
    _progressController.dispose();
    super.dispose();
  }

  /// 初始化动画
  /// Initialize animations
  void _initAnimations() {
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 1200),
      vsync: this,
    );
    
    _progressController = AnimationController(
      duration: const Duration(milliseconds: 2000),
      vsync: this,
    );
    
    // 创建项目动画
    // Create item animations
    _itemAnimations = List.generate(4, (index) {
      return Tween<double>(
        begin: 0.0,
        end: 1.0,
      ).animate(CurvedAnimation(
        parent: _animationController,
        curve: Interval(
          index * 0.2,
          (index * 0.2) + 0.6,
          curve: Curves.easeOutCubic,
        ),
      ));
    });
    
    // 创建进度动画
    // Create progress animation
    _progressAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _progressController,
      curve: Curves.easeOutCubic,
    ));
    
    // 启动动画
    // Start animations
    _animationController.forward();
    _progressController.forward();
  }

  /// 获取今日统计数据
  /// Get today's statistics
  Map<String, dynamic> _getTodayStats() {
    final todayRecords = _emotionController.todayRecords;
    
    if (todayRecords.isEmpty) {
      return {
        'recordCount': 0,
        'averageIntensity': 0.0,
        'dominantEmotion': null,
        'emotionDistribution': <String, int>{},
        'moodTrend': 'stable',
      };
    }
    
    // 计算记录数量
    // Calculate record count
    final recordCount = todayRecords.length;
    
    // 计算平均强度
    // Calculate average intensity
    final totalIntensity = todayRecords.fold<int>(
      0,
      (sum, record) => sum + record.emotionIntensity,
    );
    final averageIntensity = totalIntensity / recordCount;
    
    // 计算情绪分布
    // Calculate emotion distribution
    final emotionDistribution = <String, int>{};
    for (final record in todayRecords) {
      final emotionType = record.emotionType.value;
      emotionDistribution[emotionType] = 
          (emotionDistribution[emotionType] ?? 0) + 1;
    }
    
    // 找出主导情绪
    // Find dominant emotion
    String? dominantEmotion;
    int maxCount = 0;
    emotionDistribution.forEach((emotion, count) {
      if (count > maxCount) {
        maxCount = count;
        dominantEmotion = emotion;
      }
    });
    
    // 计算情绪趋势
    // Calculate mood trend
    String moodTrend = 'stable';
    if (todayRecords.length >= 2) {
      final firstHalf = todayRecords.take(todayRecords.length ~/ 2);
      final secondHalf = todayRecords.skip(todayRecords.length ~/ 2);
      
      final firstAvg = firstHalf.fold<double>(
        0,
        (sum, record) => sum + record.emotionIntensity,
      ) / firstHalf.length;
      
      final secondAvg = secondHalf.fold<double>(
        0,
        (sum, record) => sum + record.emotionIntensity,
      ) / secondHalf.length;
      
      if (secondAvg > firstAvg + 1) {
        moodTrend = 'improving';
      } else if (secondAvg < firstAvg - 1) {
        moodTrend = 'declining';
      }
    }
    
    return {
      'recordCount': recordCount,
      'averageIntensity': averageIntensity,
      'dominantEmotion': dominantEmotion,
      'emotionDistribution': emotionDistribution,
      'moodTrend': moodTrend,
    };
  }

  /// 获取趋势图标和颜色
  /// Get trend icon and color
  Map<String, dynamic> _getTrendInfo(String trend) {
    switch (trend) {
      case 'improving':
        return {
          'icon': Icons.trending_up,
          'color': AppColors.success,
          'text': '情绪向好',
        };
      case 'declining':
        return {
          'icon': Icons.trending_down,
          'color': AppColors.warning,
          'text': '需要关注',
        };
      default:
        return {
          'icon': Icons.trending_flat,
          'color': AppColors.info,
          'text': '情绪平稳',
        };
    }
  }

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      final stats = _getTodayStats();
      
      return GestureDetector(
        onTap: widget.clickable ? () => AppRoutes.toAnalytics() : null,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 标题行
            // Title row
            _buildTitleRow(stats),
            
            const SizedBox(height: AppConstants.spacingMedium),
            
            if (stats['recordCount'] == 0)
              _buildEmptyState()
            else ...[
              // 统计卡片
              // Statistics cards
              _buildStatisticsCards(stats),
              
              if (widget.showDetails) ...[
                const SizedBox(height: AppConstants.spacingMedium),
                
                // 情绪分布
                // Emotion distribution
                _buildEmotionDistribution(stats),
              ],
            ],
          ],
        ),
      );
    });
  }

  /// 构建标题行
  /// Build title row
  Widget _buildTitleRow(Map<String, dynamic> stats) {
    final trendInfo = _getTrendInfo(stats['moodTrend']);
    
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Row(
          children: [
            Icon(
              Icons.today,
              color: AppColors.primary,
              size: 24,
            ),
            const SizedBox(width: AppConstants.spacingSmall),
            Text(
              '今日总结',
              style: AppTextStyles.titleMedium.copyWith(
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
        
        if (stats['recordCount'] > 0)
          AnimatedBuilder(
            animation: _itemAnimations[0],
            builder: (context, child) {
              return FadeTransition(
                opacity: _itemAnimations[0],
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 4,
                  ),
                  decoration: BoxDecoration(
                    color: trendInfo['color'].withOpacity(0.1),
                    borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                    border: Border.all(
                      color: trendInfo['color'].withOpacity(0.3),
                      width: 1,
                    ),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(
                        trendInfo['icon'],
                        size: 16,
                        color: trendInfo['color'],
                      ),
                      const SizedBox(width: 4),
                      Text(
                        trendInfo['text'],
                        style: AppTextStyles.bodySmall.copyWith(
                          color: trendInfo['color'],
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ],
                  ),
                ),
              );
            },
          ),
      ],
    );
  }

  /// 构建空状态
  /// Build empty state
  Widget _buildEmptyState() {
    return AnimatedBuilder(
      animation: _itemAnimations[0],
      builder: (context, child) {
        return FadeTransition(
          opacity: _itemAnimations[0],
          child: Container(
            width: double.infinity,
            padding: const EdgeInsets.symmetric(
              vertical: AppConstants.paddingLarge,
            ),
            child: Column(
              children: [
                Icon(
                  Icons.sentiment_neutral,
                  size: 48,
                  color: AppColors.textSecondary,
                ),
                const SizedBox(height: AppConstants.spacingMedium),
                Text(
                  '今天还没有记录',
                  style: AppTextStyles.bodyLarge.copyWith(
                    color: AppColors.textSecondary,
                  ),
                ),
                const SizedBox(height: AppConstants.spacingSmall),
                Text(
                  '开始记录你的第一个情绪吧',
                  style: AppTextStyles.bodyMedium.copyWith(
                    color: AppColors.textTertiary,
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 构建统计卡片
  /// Build statistics cards
  Widget _buildStatisticsCards(Map<String, dynamic> stats) {
    final recordCount = stats['recordCount'] as int;
    final averageIntensity = stats['averageIntensity'] as double;
    final dominantEmotion = stats['dominantEmotion'] as String?;
    
    return Row(
      children: [
        // 记录数量
        // Record count
        Expanded(
          child: AnimatedBuilder(
            animation: _itemAnimations[1],
            builder: (context, child) {
              return FadeTransition(
                opacity: _itemAnimations[1],
                child: _buildStatCard(
                  icon: Icons.edit_note,
                  label: '记录次数',
                  value: '$recordCount',
                  color: AppColors.primary,
                ),
              );
            },
          ),
        ),
        
        const SizedBox(width: AppConstants.spacingMedium),
        
        // 平均强度
        // Average intensity
        Expanded(
          child: AnimatedBuilder(
            animation: _itemAnimations[2],
            builder: (context, child) {
              return FadeTransition(
                opacity: _itemAnimations[2],
                child: _buildStatCard(
                  icon: Icons.speed,
                  label: '平均强度',
                  value: averageIntensity.toStringAsFixed(1),
                  color: AppColors.secondary,
                ),
              );
            },
          ),
        ),
        
        if (dominantEmotion != null) ...[
          const SizedBox(width: AppConstants.spacingMedium),
          
          // 主导情绪
          // Dominant emotion
          Expanded(
            child: AnimatedBuilder(
              animation: _itemAnimations[3],
              builder: (context, child) {
                return FadeTransition(
                  opacity: _itemAnimations[3],
                  child: _buildStatCard(
                    icon: EmotionConstants.getEmotionIcon(dominantEmotion),
                    label: '主导情绪',
                    value: EmotionConstants.getEmotionLabel(dominantEmotion),
                    color: EmotionConstants.getEmotionColor(dominantEmotion),
                  ),
                );
              },
            ),
          ),
        ],
      ],
    );
  }

  /// 构建统计卡片
  /// Build stat card
  Widget _buildStatCard({
    required IconData icon,
    required String label,
    required String value,
    required Color color,
  }) {
    return Container(
      padding: const EdgeInsets.all(AppConstants.paddingMedium),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
        border: Border.all(
          color: color.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Column(
        children: [
          Icon(
            icon,
            color: color,
            size: 24,
          ),
          const SizedBox(height: AppConstants.spacingSmall),
          Text(
            value,
            style: AppTextStyles.titleMedium.copyWith(
              color: color,
              fontWeight: FontWeight.bold,
            ),
          ),
          Text(
            label,
            style: AppTextStyles.bodySmall.copyWith(
              color: AppColors.textSecondary,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  /// 构建情绪分布
  /// Build emotion distribution
  Widget _buildEmotionDistribution(Map<String, dynamic> stats) {
    final distribution = stats['emotionDistribution'] as Map<String, int>;
    final totalRecords = stats['recordCount'] as int;
    
    if (distribution.isEmpty) return const SizedBox.shrink();
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '情绪分布',
          style: AppTextStyles.titleSmall.copyWith(
            fontWeight: FontWeight.w600,
          ),
        ),
        
        const SizedBox(height: AppConstants.spacingSmall),
        
        ...distribution.entries.map((entry) {
          final emotionType = entry.key;
          final count = entry.value;
          final percentage = (count / totalRecords * 100).round();
          final color = EmotionConstants.getEmotionColor(emotionType);
          final label = EmotionConstants.getEmotionLabel(emotionType);
          final emoji = EmotionConstants.getEmotionEmoji(emotionType);
          
          return Container(
            margin: const EdgeInsets.only(bottom: AppConstants.spacingSmall),
            child: Row(
              children: [
                // 情绪标识
                // Emotion identifier
                if (emoji.isNotEmpty)
                  Text(
                    emoji,
                    style: const TextStyle(fontSize: 16),
                  )
                else
                  Icon(
                    EmotionConstants.getEmotionIcon(emotionType),
                    size: 16,
                    color: color,
                  ),
                
                const SizedBox(width: AppConstants.spacingSmall),
                
                // 标签
                // Label
                Text(
                  label,
                  style: AppTextStyles.bodyMedium.copyWith(
                    fontWeight: FontWeight.w500,
                  ),
                ),
                
                const SizedBox(width: AppConstants.spacingSmall),
                
                // 进度条
                // Progress bar
                Expanded(
                  child: AnimatedBuilder(
                    animation: _progressAnimation,
                    builder: (context, child) {
                      return LinearProgressIndicator(
                        value: (percentage / 100) * _progressAnimation.value,
                        backgroundColor: color.withOpacity(0.2),
                        valueColor: AlwaysStoppedAnimation<Color>(color),
                        minHeight: 6,
                      );
                    },
                  ),
                ),
                
                const SizedBox(width: AppConstants.spacingSmall),
                
                // 百分比
                // Percentage
                Text(
                  '$percentage%',
                  style: AppTextStyles.bodySmall.copyWith(
                    color: color,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
          );
        }).toList(),
      ],
    );
  }
}